﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Simple.Common.Core.Collections.Extensions
{
    public static class SelectListExtensions
    {
        public static List<SelectListItem> ToSelectList<T>(this IEnumerable<T> source, Func<T, object> text, Func<T, object> value, Func<T, bool> selected = null, string optionalText = "请选择")
        {
            var items = new List<SelectListItem>();
            if (optionalText != null)
            {
                items.Add(new SelectListItem() { Text = optionalText, Value = string.Empty });
            }
            if (source == null || source.Count()==0)
            {
                return items;
            }
            foreach (var entity in source)
            {
                var item = new SelectListItem();
                item.Text = text(entity).ToString();
                item.Value = value(entity).ToString();
                if (selected != null)
                {
                    item.Selected = selected(entity);
                }
                items.Add(item);
            }
            return items;
        }
    }
}
